use crate::advanced_proxy::{AdvancedClientProxy, RequestInterceptor, ResponseInterceptor, CacheConfig};
use crate::client::*;
use rustcloud_core::*;
use rustcloud_core::config_builder::{ConnectionPoolConfig, RetryConfig, TimeoutConfig, ConfigFactory};
use rustcloud_circuit_breaker::AdvancedCircuitBreaker;
use std::sync::Arc;
use std::time::Duration;

pub struct AdvancedProxyBuilder {
    registry: Option<Arc<dyn ServiceRegistry>>,
    load_balancer: Option<Arc<dyn LoadBalancer>>,
    transport: Option<Arc<dyn Transport>>,
    circuit_breaker: Option<Arc<AdvancedCircuitBreaker>>,
    config: ProxyConfig,
    service_name: String,
}

impl AdvancedProxyBuilder {
    pub fn new(service_name: String) -> Self {
        Self {
            registry: None,
            load_balancer: None,
            transport: None,
            circuit_breaker: None,
            config: Self::default_config(),
            service_name,
        }
    }
    
    pub fn registry(mut self, registry: Arc<dyn ServiceRegistry>) -> Self {
        self.registry = Some(registry);
        self
    }
    
    pub fn load_balancer(mut self, load_balancer: Arc<dyn LoadBalancer>) -> Self {
        self.load_balancer = Some(load_balancer);
        self
    }
    
    pub fn transport(mut self, transport: Arc<dyn Transport>) -> Self {
        self.transport = Some(transport);
        self
    }
    
    pub fn circuit_breaker(mut self, circuit_breaker: Arc<AdvancedCircuitBreaker>) -> Self {
        self.circuit_breaker = Some(circuit_breaker);
        self
    }
    
    pub async fn build(self) -> Result<AdvancedClientProxy, String> {
        let registry = self.registry.ok_or("Registry required")?;
        let load_balancer = self.load_balancer.ok_or("LoadBalancer required")?;
        let transport = self.transport.ok_or("Transport required")?;
        let circuit_breaker = self.circuit_breaker.ok_or("CircuitBreaker required")?;
        
        let proxy = AdvancedClientProxy::new(
            registry, load_balancer, transport, circuit_breaker, self.config
        );
        
        // Add default interceptors
        proxy.add_request_interceptor(Arc::new(LoggingInterceptor::new())).await;
        proxy.add_response_interceptor(Arc::new(LoggingInterceptor::new())).await;
        
        Ok(proxy)
    }
    
    fn default_config() -> ProxyConfig {
        ProxyConfig {
            // 使用统一的配置构建器创建标准配置
            retry: ConfigFactory::create_fast_retry(),
            timeout: TimeoutConfig::builder()
                .connect_timeout(Duration::from_secs(10))
                .request_timeout(Duration::from_secs(30))
                .idle_timeout(Duration::from_secs(60))
                .build()
                .expect("Failed to build timeout config"),
            connection_pool: ConfigFactory::create_dev_connection_pool(),
            circuit_breaker: None,
        }
    }
}
